package factory

import (
	"apibe/single/src/v1/factory/roads"
	"apibe/single/src/v1/factory/shortcut"
	"apibe/single/src/v1/factory/tools"
	"apibe/single/src/v1/share/db"
	"context"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
)

// Design 图纸 所有的接口都按照这块内容进行组装
type Design struct {
	ID               primitive.ObjectID     `json:"_id,omitempty" bson:"_id,omitempty"`
	GroupName        string                 `json:"group_name,required" bson:"group_name,required"`
	ApiName          string                 `json:"api_name,required" bson:"api_name,required"`
	Description      string                 `json:"description,required" bson:"description,required"`
	Data             Data                   `json:"data" bson:"data"`
	RequestFunction  roads.RequestFunction  `json:"request_function" bson:"request_function"`
	ResponseFunction roads.ResponseFunction `json:"response_function" bson:"response_function"`
	Format           shortcut.Formats       `json:"format" bson:"format"`
	Cache            shortcut.Cache         `json:"cache" bson:"cache"`
	HoldUser         string                 `json:"hold_user" bson:"hold_user"`
	FixDate          int64                  `json:"fix_date" bson:"fix_date"`
	Status           Status                 `json:"status" bson:"status"`
	Task             bool                   `json:"task" bson:"-"`
	Logger           []logger               `json:"log" bson:"-"`
}

type Data struct {
	Method      string          `json:"method,required" bson:"method,required"`
	Url         string          `json:"url,required" bson:"url,required"`
	ContentType string          `json:"Content-Type" bson:"Content-Type"`
	Body        string          `json:"body" bson:"body"`
	Argument    tools.Arguments `json:"argument" bson:"argument"`
}

type Status uint8

const (
	NeedCheck Status = iota // 需要审查
	Working                 // 已被审查 工作中
	Unused                  // 弃用  弃用

	Deleted // 逻辑删除 (不可见) 在程序编写中总应该是最大的一位数字
)

const (
	None             = ""
	ApplicationXml   = "application/xml"
	ApplicationJson  = "application/json"
	ApplicationJS    = "application/javascript"
	ApplicationXForm = "application/x-www-form-urlencoded"
	FormData         = "multipart/form-data"
	Text             = "text/plain"
	Html             = "text/html"
)

// 铅笔：一些对design的操作会放在这里
const (
	_apiName = "api_name"
)

// DesignList 刷新图纸集合
var DesignList []Design

// GetDesign 根据 apiName 获取 design
func GetDesign(apiName string) (*Design, error) {
	for _, design := range DesignList { // design
		if design.ApiName == apiName {
			return &design, nil
		}
	}
	var d Design
	err := db.GetMongoCollection(db.CollectionDesign).FindOne(context.Background(), bson.M{_apiName: apiName}).Decode(&d)
	return &d, err
}
